<template>
    <div class="addedit">
        <el-form :model="ruleForm" label-width="150px" :rules="rules" ref="ruleFormRef">
            <el-form-item label="品牌名称：" prop="name">
                <el-input v-model="ruleForm.name" />
            </el-form-item>
            <el-form-item label="品牌首字母：" prop="firstLetter">
                <el-input v-model="ruleForm.firstLetter" />
            </el-form-item>
            <el-form-item label="品牌logo：" prop="logo">
                <el-upload ref="upload" class="upload-demo" action="http://120.24.64.5:8088/mall-admin/minio/upload"
                    :limit="1" :on-exceed="handleExceed" list-type="picture" :before-upload="beforeAvatarUpload"
                    :on-success="handleAvatarSuccess" v-model:file-list="fileList" :on-remove="handleRemove">
                    <template #trigger>
                        <el-button type="primary">点击上传</el-button>
                    </template>
                    <template #tip>
                        <div class="el-upload__tip">
                            只能上传jpg/png文件，且不超过100kb
                        </div>
                    </template>
                </el-upload>
            </el-form-item>

            <el-form-item label="品牌专区大图：" prop="bigPic">
                <el-upload ref="uploadPic" class="upload-demo" action="http://120.24.64.5:8088/mall-admin/minio/upload"
                    :limit="1" :on-exceed="handleExceedPic" list-type="picture" :before-upload="beforeAvatarUpload"
                    :on-success="handleAvatarSuccessPic" v-model:file-list="fileListPic" :on-remove="handleRemovePic">
                    <template #trigger>
                        <el-button type="primary">点击上传</el-button>
                    </template>
                    <template #tip>
                        <div class="el-upload__tip">
                            只能上传jpg/png文件，且不超过100kb
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item label="品牌故事：" prop="brandStory">
                <el-input />
            </el-form-item>
            <el-form-item label="排序：" prop="sort">
                <el-input v-model="ruleForm.sort" />
            </el-form-item>
            <el-form-item label="是否显示：" prop="showStatus">
                <el-radio-group v-model="ruleForm.showStatus">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="是否显示品牌制造商：" prop="factoryStatus">
                <el-radio-group v-model="ruleForm.factoryStatus">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
                <el-button type="default" @click="resetForm(ruleFormRef)" v-show="!route.query.id">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, toRefs } from 'vue';
import { ElMessage, ElMessageBox, FormInstance, FormRules, genFileId, UploadInstance, UploadProps, UploadRawFile, UploadUserFile } from 'element-plus'
import { pro } from '@/api'
import { useRoute, useRouter } from 'vue-router';
const route = useRoute()
const router = useRouter()
const state = reactive<{ ruleForm: IProBrandsParams }>({
    ruleForm: {
        bigPic: '',
        brandStory: '',
        factoryStatus: 0,
        firstLetter: '',
        logo: '',
        name: '',
        showStatus: 0,
        sort: 0
    },
})
let { ruleForm } = toRefs(state);
const ruleFormRef = ref<FormInstance>()
if (route.query.id) {
    pro.getIDProBrandApi(parseInt(route.query.id as string)).then(res => {
        console.log(res);
        if (res.code === 200) {
            state.ruleForm = res.data;
            if (res.data.logo) {
                fileList.value = [{ name: res.data.logo.substr((res.data.logo.lastIndexOf("/")) + 1), url: res.data.logo }]
            }
            if (res.data.bigPic) {
                fileListPic.value = [{ name: res.data.bigPic.substr((res.data.bigPic.lastIndexOf("/")) + 1), url: res.data.bigPic }]
            }
        }
    })
}

// 校验
const rules = reactive<FormRules>({
    name: [
        { required: true, message: '请输入分类名称', trigger: 'blur' },
    ],
    logo: [
        { required: true, message: '请上传logo', trigger: 'blur' },
    ],
})
// 提交
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 发请求
            ElMessageBox.confirm(
                '确定要提交数据吗？', '提示',
            ).then(() => {
                if (route.query.id) {
                    pro.updateProBrandApi({ id: Number(route.query.id), editParams: state.ruleForm }).then(res => {
                        if (res.code === 200) {
                            ElMessage.success('提交成功');
                            formEl.resetFields()
                            router.push('/pms/brand')
                        }
                    })
                } else {
                    pro.createProBrandApi(state.ruleForm).then(res => {
                        if (res.code === 200) {
                            ElMessage.success('提交成功')
                            formEl.resetFields()
                            router.push('/pms/brand')
                        }
                    })
                }

            })

        } else {
            return false
        }
    })
}
// 重置
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
//上传文件
const upload = ref<UploadInstance>()
const uploadPic = ref<UploadInstance>()
const fileList = ref<UploadUserFile[]>([])
const fileListPic = ref<UploadUserFile[]>([])
// 个数限制
const handleExceed: UploadProps['onExceed'] = (files) => {
    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload.value!.handleStart(file)
}
const handleExceedPic: UploadProps['onExceed'] = (files) => {
    uploadPic.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadPic.value!.handleStart(file)
}
// :auto-upload="false"
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('只能上传.jpg或.png格式的 文件！')
        return false
    } else if (rawFile.size / 1024 > 100) {
        ElMessage.error('上传的图片不能超过100K!')
        return false
    }
    return true
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    fileList.value = []
    fileList.value.push(response.data)
    state.ruleForm.logo = response.data.url
    console.log(fileList.value);

}
const handleAvatarSuccessPic: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    fileListPic.value = []
    fileListPic.value.push(response.data)
    state.ruleForm.bigPic = response.data.url
}
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    state.ruleForm.logo = ''
}
const handleRemovePic: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    state.ruleForm.bigPic = ''
}
</script>

<style scoped lang="less">
.addedit {
    border: 1px solid #ebeef5;
    padding: 50px 100px;
    margin: 20px;
}

.select-attr {
    width: 500px;
    display: flex;
    flex-wrap: wrap;
}

.attr-item {
    margin: 20px 0;

    .el-button {
        margin-left: 20px;
    }
}
</style>